package cn.tedu.order.service;


import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private OrderTccAction tcc;

    @GlobalTransactional
    @Transactional //控制本地事务
    @Override
    public void create(Order order) {
        //远程调用发号器,获取订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);

        order.setId(orderId);
        /**
         * 第一个参数上下文对象:在tcc的动态代理对象中,通过AOP添加了前置通知,
         * 在前置代码中会创建上下文对象
         */
        //不直接正常的创建订单,而是调用TCCaction一阶段方法
        //orderMapper.create(order);
        tcc.prepare(null,
                order.getId(),
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());

        //远程调用库存,减少库存
        storageClient.decrease(order.getProductId(),order.getCount());
        //远程调用账户,扣减账户
        //accountClient.decrease(order.getUserId(),order.getMoney());
    }
}